package com.bodacn.keypoint;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.app.AppCompatActivity;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.view.View.GONE;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;


public class QuestionActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG=this.getClass().getName();
    private final int MSG_QuestionOver=1001;
    private final int MSG_FocusDefaultItem =1002;
    private final int MSG_DetailOver=1003;
    private final int MSG_ReasonOver=1004;
    private final int MSG_ViewHisDetail=1005;
    public static final int titleHeight=50;
    Button btn_tmpSave,btn_Submit,btn_Return,btn_Clear,btn_Update,btn_Part,btn_Reason;
    GridView titleGrid,questionGrid;
    ListView detailList;
    TextView txt_QuestionCodes;
    ImageView imageLayout;
    PictureTagLayout ptlayout;
    JSONArray typeJson,itemJson,detailJson,questionJson,partJson,headJSON,selectItemJson,reasonJson;
    SQLiteDatabase tmpdb;
    ArrayList<PointPlace> points;
    String STORE_NAME = "Settings";
    String SaveFilePath="",SaveDBFolder="/DB";
    public static final String DB_Name ="bdmes.db";
    Toast curToast;
    View tmpItemView;
    int tmpItemIndex=-1;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID,curTitleInv,selImageFile="",ClipType="",NeedPos="YES";
    String selOrderNo="",selStyleNo="",selStyleSort="",selReason="";
    String selPartName;
    String curQuestionNo="";
    int curItemIdex=-1;
    int MaxPieces=5;
    LinearLayout templetlisthead;
    ListView selectTempletList;
    TextView tv_QuestionInv;
    EditText clampBarcode;
    TextView clampHint;
    private View touchView,newView;
    boolean allowAdd=true;
    int startX ;
    int startY ;
    int startTouchViewLeft = 0;
    int startTouchViewTop = 0;
    private int height;
    private int width;
    private int endX;
    private int endY;
    private int toWhere;
    float xDown,yDown,xUp;
    private static final int CLICKRANGE = 5;
    //拦截扫描枪输入部分
    String BarcodeStr="",clampNo="";
    ScannerManager scannerManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question);
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNo");
        curDepart=paramBundle.getString("CurDepart");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        curTitleInv=paramBundle.getString("TitleInv");
        selImageFile=paramBundle.getString("selImageFile");
        ClipType=paramBundle.getString("ClipType");
        MaxPieces=paramBundle.getInt("MaxPieces");
        CPUID=paramBundle.getString("CPUID");
        selOrderNo=paramBundle.getString("selOrderNo");
        selStyleNo=paramBundle.getString("selStyleNo");
        selStyleSort=paramBundle.getString("selStyleSort");
        clampNo=paramBundle.getString("clampNo","");
        String prjson=paramBundle.getString("questionJson","[]");
        try {
            detailJson=new JSONArray(prjson);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println("detailJson:"+detailJson);
        NeedPos=paramBundle.getString("NeedPos","YES");//图片标注
        InitView();
        if ((curTitleInv!=null)&&(curTitleInv.length()>0)) ((TextView)findViewById(R.id.txt_titleInv)).setText(curTitleInv);
        //控件界面
        if ((ClipType!=null)&&(ClipType.length()>0)){
            if (ClipType.equals("Single")==true){
                btn_tmpSave.setVisibility(GONE);
                btn_Clear.setVisibility(GONE);
                detailList.setVisibility(GONE);
                clampBarcode.setVisibility(View.GONE);
                clampHint.setVisibility(View.GONE);
                findViewById(R.id.bottomview).setVisibility(GONE);
            }
            if (ClipType.equals("multi")==true){
                //btn_Reason.setVisibility(GONE);
                //findViewById(R.id.tv_Reason).setVisibility(GONE);
                tv_QuestionInv.setVisibility(GONE);
                clampBarcode.setVisibility(View.VISIBLE);
                clampHint.setVisibility(View.VISIBLE);

            }
        }
        clampBarcode.setText(clampNo);
        selPartName="";
        btn_Part.setText("未定义");
        btn_Reason.setText("未选择");
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code,String deviceName) {
                Log.d(TAG, "code= " + code);
                playRingtone();
                clampBarcode.setText(code);
            }
        },this);

    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+this.getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }
    //初始化;
    public void InitView(){
        points=new ArrayList<>();
        clampBarcode=findViewById(R.id.clampBarcode);
        clampHint=findViewById(R.id.clampHint);
        ptlayout=findViewById(R.id.ptlayout);
        btn_tmpSave=findViewById(R.id.btn_tmpSave);
        btn_tmpSave.setOnClickListener(this);
        btn_Submit=findViewById(R.id.btn_Submit);
        btn_Submit.setOnClickListener(this);
        btn_Return=findViewById(R.id.btn_Return);
        btn_Return.setOnClickListener(this);
        btn_Clear=findViewById(R.id.btn_Clear);
        btn_Clear.setOnClickListener(this);
        btn_Update=findViewById(R.id.btn_Update);
        btn_Update.setOnClickListener(this);
        ((Button)findViewById(R.id.btn_ClearQuestion)).setOnClickListener(this);
        //文本
        btn_Part=findViewById(R.id.btn_Part);
        btn_Part.setOnClickListener(this);
        btn_Part.setBackground(getResources().getDrawable(R.drawable.btn_back_dec));
        txt_QuestionCodes=findViewById(R.id.txt_QuestionCodes);
        btn_Reason=findViewById(R.id.btn_Reason);
        btn_Reason.setOnClickListener(this);
        btn_Reason.setBackground(getResources().getDrawable(R.drawable.btn_back_dec));
        tv_QuestionInv=findViewById(R.id.tv_QuestionInv);
        //图片
        imageLayout=findViewById(R.id.imageLayout);
        ptlayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                System.out.println("event:"+event);
                float opstX=event.getRawX();
                float opstY=event.getRawY()-titleHeight;//减去标题高度58
                //根据点击的位置获取部件
                PointPlace pointPlace1 = new PointPlace();
                pointPlace1.width_scale=opstX/v.getWidth();
                pointPlace1.height_scale=opstY/v.getHeight();
                points.clear();
                points.add(pointPlace1);
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        GetPartName(pointPlace1.width_scale*100,pointPlace1.height_scale*100);
                        System.out.println("width_scale:"+pointPlace1.width_scale+"  height_scale:"+pointPlace1.height_scale);
                        points.clear();
                        points.add(pointPlace1);
                        touchView = null;
                        startX = (int) event.getX();
                        startY = (int) event.getY();
                        touchView=ptlayout.hasView(startX,startY);
                        if(touchView!=null){//如果点击位置已经有了
                            startTouchViewLeft = touchView.getLeft();
                            startTouchViewTop = touchView.getTop();
                            curToast.setText("当前位置有疵点");
                            curToast.show();
                        } else {
                            //增加触点
                            if (allowAdd) {
                                String brandid="";
                                if (detailJson!=null) brandid=String.valueOf(detailJson.length()+1);
                                else brandid="1";
                                newView=ptlayout.addItem((int)opstX,(int)opstY,"新标签,请选择疵点",brandid,0,"L");
                                allowAdd=false;
                            }
                        }
                        Log.i("******点击的位置--x-", startX + "*----y"+startY);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        ptlayout.moveView((int) event.getX(),
                                (int) event.getY(),touchView);
                        if((int) event.getX()>startX){//向右滑动标签view
                            toWhere=1;
                        }else{
                            toWhere=2;
                        }
                        System.out.println("width_scale:"+pointPlace1.width_scale+"  height_scale:"+pointPlace1.height_scale);
                        break;
                    case MotionEvent.ACTION_UP:
                        xUp = event.getX();
                        Log.v("OnTouchListener", "Up");
                        //按下和松开绝对值差当大于20时滑动，否则不显示
                        if ((xUp - xDown) > 20)
                        {
                            //添加要处理的内容
                        }
                        else if((xUp - xDown ) < -20)
                        {
                            //添加要处理的内容
                        }
                        else if( 0 == (xDown - xUp))
                        {
                            int viewWidth = v.getWidth();
                            if( xDown < viewWidth/3 )
                            {
                                //靠左点击
                            }
                            else if(xDown > viewWidth/3 && xDown < viewWidth * 2 /3)
                            {
                                //中间点击
                            }
                            else
                            {
                                //靠右点击
                            }
                        }
                        endX = (int) event.getX();
                        endY = (int) event.getY();
                        GetPartName(pointPlace1.width_scale*100,pointPlace1.height_scale*100);
                        //如果挪动的范围很小，则判定为单击   单击换背景图片
                        if(touchView!=null&& Math.abs(endX - startX)<CLICKRANGE&& Math.abs(endY - startY)<CLICKRANGE){
                            touchView=ptlayout.hasView(endX,endY);
                            if(touchView!=null){//如果点击位置已经有了
                                if ("L".equals(((PictureTagView)touchView).getDirection())){
                                    Log.i("----direct---L",((PictureTagView)touchView).getDirection());
                                    ((PictureTagView)touchView).directionChange(PictureTagView.Direction.Right);
                                }else if ("R".equals(((PictureTagView)touchView).getDirection())){
                                    Log.i("----direct---R",((PictureTagView)touchView).getDirection());
                                    ((PictureTagView)touchView).directionChange(PictureTagView.Direction.Left);
                                    Log.i("---direct----",((PictureTagView)touchView).getDirection());
                                }
                            } else {
                                //showPopup();
                            }
                        }
                        if (touchView!=null&&detailJson!=null){
                            String brandID=((PictureTagView)touchView).getBrandId();
                            if (brandID.length()>0){
                                int postion=Integer.parseInt(brandID);
                                System.out.println(postion);
                                if (postion>0&&postion<=detailJson.length()) {
                                    try {
                                        detailJson.optJSONObject(postion-1).put("PosX",pointPlace1.width_scale);
                                        detailJson.optJSONObject(postion-1).put("PosY",pointPlace1.height_scale);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                        break;
                    default:
                        break;

                }
                return true;
            }
            /*
            PointPlace pointPlace1 = new PointPlace();
            pointPlace1.width_scale=opstX/v.getWidth();
            pointPlace1.height_scale=opstY/v.getHeight();
                System.out.println("width_scale:"+pointPlace1.width_scale+"  height_scale:"+pointPlace1.height_scale);
                points.clear();
                points.add(pointPlace1);
            //根据点击的位置获取部件
            GetPartName(pointPlace1.width_scale*100,pointPlace1.height_scale*100);
                System.out.println(pointPlace1.width_scale+"----"+pointPlace1.height_scale);

             */
        });

        //表格;
        titleGrid=findViewById(R.id.titleGrid);
        titleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                view.setSelected(true);
                try {
                    if (tmpItemIndex==-1) {
                        GetItem(typeJson.optJSONObject(i).getString("QuestionType"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        questionGrid=findViewById(R.id.questionGrid);
        questionGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                view.setSelected(true);
                TextView item_QuestionCode = (TextView) view.findViewById(R.id.item_QuestionCode);
                String tmpQuestion = txt_QuestionCodes.getText().toString();
                if (ClipType.toUpperCase().equals("SINGLE")) {
                    if (tmpQuestion.length() > 0) {
                        if (tmpQuestion.indexOf(item_QuestionCode.getText().toString()) == -1)
                            tmpQuestion = tmpQuestion + ',' + item_QuestionCode.getText().toString();
                    } else tmpQuestion = item_QuestionCode.getText().toString();
                } else{
                    System.out.println("questionGrid:setOnItemClickListener--1");
                    tmpQuestion=item_QuestionCode.getText().toString();
                    if (itemJson.optJSONObject(i).has("QuestionNum")){
                        try {
                            curQuestionNo=itemJson.optJSONObject(i).getString("QuestionNo");
                            curItemIdex=i;
                            System.out.println("questionGrid:setOnItemClickListener--2");
                            int QuestionNum=itemJson.optJSONObject(i).getInt("QuestionNum");
                            itemJson.optJSONObject(i).put("QuestionNum",QuestionNum+1);
                            tmpdb.execSQL("update QCQuestion set QuestionNum=? where QuestionNo=?",
                                    new Object[]{QuestionNum+1,curQuestionNo});
                            ((ItemGridAdapter)questionGrid.getAdapter()).notifyDataSetChanged();
                            System.out.println("questionGrid:setOnItemClickListener--3");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }
                System.out.println(tmpQuestion);
                txt_QuestionCodes.setText(tmpQuestion);
            }
        });
        detailList =findViewById(R.id.colorsizeList);
        detailList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });

        //初始提醒;
        curToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
        curToast.setGravity(Gravity.CENTER, 0, 0);
        hideBottomUIMenu();
    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }
    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理 * * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (tmpdb==null) OpenCreateDB();
        tmpdb.execSQL("update QCQuestion set QuestionNum=0");
        GetType();
        refreshPart();
        //显示图片;
        showImage();
        //显示上一界面带来的明细
        if (!ClipType.toUpperCase().equals("SINGLE")) {
            //刷新界面;
            Message msg = new Message();
            msg.what = MSG_ViewHisDetail;
            handler.removeMessages(msg.what);
            handler.sendMessage(msg);
        }
    }

    //刷新部件
    private void refreshPart() {
        System.out.println("refreshPart()");
        if (tmpdb==null) OpenCreateDB();
        try {
            DecimalFormat df= new DecimalFormat("######0.00");
            partJson=new JSONArray("[]");
            Cursor cur=tmpdb.rawQuery("Select  * from  PartDefine order by PosX,PosY",null);
            while (cur.moveToNext()){
                JSONObject tmpObj=new JSONObject();
                tmpObj.put("PartName",cur.getString(cur.getColumnIndex("PartName")));
                tmpObj.put("PosX",df.format(cur.getFloat(cur.getColumnIndex("PosX"))));
                tmpObj.put("PosY",df.format(cur.getFloat(cur.getColumnIndex("PosY"))));
                partJson.put(tmpObj);
                System.out.println(cur.getString(cur.getColumnIndex("PartName"))+":"+cur.getLong(cur.getColumnIndex("PosX"))+":"+cur.getLong(cur.getColumnIndex("PosY")));
            }
            System.out.println("partJson:"+partJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showImage() {
        String imgfilepath = getCacheDir().toString();
        File file = new File(imgfilepath + "/" + selImageFile);
        System.out.println("图片文件路径:" + imgfilepath + "/" + selImageFile);
        //判断图片是否存在，如果不存在则从网络获取;
        if (file.exists() == true) {
            Log.d(TAG, "本地有取图片---------------"+selImageFile);
            //从本地取图片
            Bitmap bitmap = getLoacalBitmap(imgfilepath + "/" + selImageFile);
            imageLayout.setImageBitmap(bitmap);
        } else{
            Drawable drawable = getResources().getDrawable(R.mipmap.err404);
            BitmapDrawable errBitDraw = (BitmapDrawable) drawable;
            imageLayout.setImageBitmap(errBitDraw.getBitmap());
        }
    }

    /**
     * @param @param  url 本地路径
     * @param @return
     * @return Bitmap
     * @throws
     * @Title: getLoacalBitmap
     * @Description: 加载本地图片
     */
    public Bitmap getLoacalBitmap(String url) {
        if (url != null) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(url);
                return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fis = null;
                }
            }
        } else {
            return null;
        }
    }

    //获取订单
    private void GetPartName(double paramPosX,double paramPosY) {
        System.out.println("GetPartName()-paramPosX:"+paramPosX+" paramPosY:"+paramPosY);
        if (tmpdb==null) OpenCreateDB();
        try {
            btn_Part.setText("未定义");
            btn_Part.setBackground(getResources().getDrawable(R.drawable.btn_back_dec));
            String sqlText="Select  * from  PartDefine where PosX>"+(paramPosX*0.9)+" and PosX<"+paramPosX*1.1+" and PosY>"
                    +paramPosY*0.9+" and PosY<"+paramPosY*1.1+" order by abs(PosX-"+paramPosX+")+abs(PosY-"+paramPosY+")";
            System.out.println(sqlText);
            Cursor cur1=tmpdb.rawQuery(sqlText,null);
            while (cur1.moveToNext()){
                btn_Part.setText(cur1.getString(cur1.getColumnIndex("PartName")));
                btn_Part.setBackground(getResources().getDrawable(R.drawable.btn_back_add));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void addPartPos(String paramPartName,double paramPosX,double paramPosY){
        try {
            DecimalFormat df= new DecimalFormat("######0.00");
            if (tmpdb == null) OpenCreateDB();
            //删除未初始化的点
            String sqlText = "delete from PartDefine where PartName='" + paramPartName + "' and (PosX<0.1 and PosY<0.1)";
            System.out.println(sqlText);
            tmpdb.execSQL(sqlText);
            //删除附近相同的点
            sqlText = "delete from PartDefine where PartName='" + paramPartName +  "' and PosX>"+(paramPosX*0.94)+" and PosX<"+(paramPosX*1.06)+" and PosY>" +(paramPosY*0.94)+" and PosY<"+(paramPosY*1.06);
            System.out.println(sqlText);
            tmpdb.execSQL(sqlText);
            //插入新部位对应的点
            sqlText = "insert into PartDefine(PartName,PosX,PosY) values('" + paramPartName + "'," + df.format(paramPosX) + "," + df.format(paramPosY) + ")";
            System.out.println(sqlText);
            tmpdb.execSQL(sqlText);
            //放入数据库定义
            sqlText = "Exec KeyPoint_AddPartPos @OrderNo='" + selOrderNo + "',@StyleNo='" + selStyleNo + "',@StyleSort='" + selStyleSort
                    + "',@PartName='" + paramPartName + "',@PosX=" + df.format(paramPosX) + ",@PosY=" + df.format(paramPosY)
                    + ",@OPERTYPE='PARTPOS',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
            ReadSQLData(sqlText);
            refreshPart();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //获取订单
    private void GetType() {
        System.out.println("GetType()");
        tmpItemView=null;
        tmpItemIndex=-1;
        String tmpType="",tmpStr="";
        if (tmpdb==null) OpenCreateDB();
        try {
            typeJson=new JSONArray("[]");
            Cursor cur=tmpdb.rawQuery("Select TypeIndex,QuestionType from  QCQuestion  Group by TypeIndex,QuestionType order by TypeIndex",null);

            while (cur.moveToNext()){
                if (tmpType.length()==0) {
                    tmpStr=cur.getString(cur.getColumnIndex("QuestionType"));
                    if (tmpStr.indexOf("缝制")>=0) tmpType=tmpStr;
                }
                JSONObject typeObj = new JSONObject();
                typeObj.put("QuestionType",cur.getString(cur.getColumnIndex("QuestionType")));
                typeJson.put(typeObj);
            }
            cur.close();
            GetItem(tmpType);
            //显示明细数据
            TypeGridAdapter typeGridAdapter=new TypeGridAdapter(getApplicationContext());
            titleGrid.setAdapter(typeGridAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    //获取明细
    private void GetItem(String paramType) {
        System.out.println("GetItem("+paramType+")");
        try {
            curItemIdex=-1;
            curQuestionNo="";
            itemJson=new JSONArray("[]");
            Cursor cur=tmpdb.rawQuery("Select * from  QCQuestion where QuestionType=? order by QuestionNo",new String[]{paramType});
            while (cur.moveToNext()){
                JSONObject itemObj = new JSONObject();
                itemObj.put("QuestionNo",cur.getString(cur.getColumnIndex("QuestionNo")));
                itemObj.put("QuestionCode",cur.getString(cur.getColumnIndex("QuestionCode")));
                itemObj.put("QuestionNum",cur.getString(cur.getColumnIndex("QuestionNum")));
                itemJson.put(itemObj);
            }
            cur.close();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //显示明细数据
        ItemGridAdapter itemGridAdapter=new ItemGridAdapter(getApplicationContext());
        questionGrid.setAdapter(itemGridAdapter);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_Update:
                GetQuestion();
                break;
            case R.id.btn_Return:
                finish();
                break;
            case R.id.btn_tmpSave:
                if (NeedPos.equals("YES")&&points.size()<=detailJson.length()) {
                    curToast.setText("请在图片上标注疵点位置后再选择疵点!");
                    curToast.show();
                    return;
                }
                String QuestionCodes=txt_QuestionCodes.getText().toString();
                //if (ClipType.toUpperCase().equals("SINGLE"))
                if (txt_QuestionCodes.getText().toString().indexOf("污") > -1
                        || txt_QuestionCodes.getText().toString().indexOf("破洞") > -1) {
                    if (btn_Part.getText().toString().equals("未定义") || btn_Reason.getText().toString().equals("未选择")) {
                        curToast.setText(txt_QuestionCodes.getText().toString() + "必须要选部位及选原因!");
                        curToast.show();
                        return;
                    }
                }
                System.out.println("疵点:" + txt_QuestionCodes.getText().toString() + "indexOf(脱拷)" + txt_QuestionCodes.getText().toString().indexOf("脱拷"));
                if (txt_QuestionCodes.getText().toString().indexOf("脱拷") > -1) {
                    if (btn_Part.getText().toString().equals("未定义")) {
                        curToast.setText(txt_QuestionCodes.getText().toString() + "必须要选部位!");
                        curToast.show();
                        return;
                    }
                }
                if (ClipType.toUpperCase().equals("SINGLE")==false)
                {
                    QuestionCodes="";
                    Cursor cur=tmpdb.rawQuery("Select * from QCQuestion where QuestionNum>0",null);
                    while (cur.moveToNext()){
                        String QuestionCode=cur.getString(cur.getColumnIndex("QuestionCode"));
                        String QuestionNum=cur.getString(cur.getColumnIndex("QuestionNum"));
                        if (QuestionCodes.length()==0) QuestionCodes=QuestionCode+":"+QuestionNum;
                        else QuestionCodes=QuestionCodes+";"+QuestionCode+":"+QuestionNum;
                    }
                    cur.close();
                }
                if (NeedPos.equals("YES")&&points.size()==0) {
                    curToast.setText("请在图片上标注疵点位置!");
                    curToast.show();
                    return;
                }
                if (points.size()==0){
                    PointPlace pointPlace1 = new PointPlace();
                    pointPlace1.width_scale=0;
                    pointPlace1.height_scale=0;
                    points.clear();
                    points.add(pointPlace1);
                }

                if (QuestionCodes.length()>0){
                    if (detailJson.length()<MaxPieces){
                        JSONObject tmpObj=new JSONObject();
                        try {
                            tmpObj.put("RowNo",detailJson.length()+1);
                            tmpObj.put("QuestionCodes",QuestionCodes);
                            tmpObj.put("Reason",btn_Reason.getText().toString());
                            tmpObj.put("PosX",points.get(points.size()-1).width_scale);
                            tmpObj.put("PosY",points.get(points.size()-1).height_scale);
                            tmpObj.put("PartName",btn_Part.getText().toString());
                            detailJson.put(tmpObj);
                            txt_QuestionCodes.setText("");
                            //增加触点
                            if (newView!=null) {
                                //标签在右面 点击位置 x-标签宽度   右边的标签并不是以圆点开始的  而是以左边的wei
                                int posHeight = newView.getMeasuredHeight();
                                int posWidth = newView.getMeasuredWidth();
                                int posLeft = newView.getLeft();
                                int posTop = newView.getTop();
                                ((PictureTagView)newView).addText(QuestionCodes);
                                newView.requestLayout();
                                ptlayout.setPostion(posLeft+posWidth-10,posTop+posHeight-5,newView);
                                allowAdd=true;
                            }
                            //显示
                            DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
                            detailList.setAdapter(detailListAdapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        curToast.setText("超过最大疵点列表!");
                        curToast.show();
                    }
                } else{
                    curToast.setText("请先选择疵点再暂存!");
                    curToast.show();
                }
                tmpdb.execSQL("Update QCQuestion set QuestionNum=0");
                for (int i=0;i<itemJson.length();i++){
                    try {
                        itemJson.optJSONObject(i).put("QuestionNum",0);
                        ((BaseAdapter)questionGrid.getAdapter()).notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.btn_Clear:
                titleGrid.performItemClick(titleGrid.getChildAt(0), 0, titleGrid.getItemIdAtPosition(0));
                ((TypeGridAdapter)titleGrid.getAdapter()).notifyDataSetChanged();
                try {
                    curItemIdex=-1;
                    curQuestionNo="";
                    ptlayout.removeAllViews();
                    txt_QuestionCodes.setText("");
                    detailJson=new JSONArray("[]");
                    points.clear();
                    tmpdb.execSQL("update QCQuestion set QuestionNum=0");
                    if (itemJson!=null&&itemJson.length()>0){
                        for (int i=0;i<itemJson.length();i++){
                            itemJson.optJSONObject(i).put("QuestionNum",0);
                        }
                    }
                    ((BaseAdapter)questionGrid.getAdapter()).notifyDataSetChanged();
                    //imageLayout.setPoints(points);
                    //显示
                    DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
                    detailList.setAdapter(detailListAdapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_ClearQuestion:
                txt_QuestionCodes.setText("");
                if (curItemIdex>-1){
                    tmpdb.execSQL("update QCQuestion set QuestionNum=0 where QuestionNo=?", new Object[]{curQuestionNo});
                    try {
                        itemJson.optJSONObject(curItemIdex).put("QuestionNum",0);
                        ((BaseAdapter)questionGrid.getAdapter()).notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                selPartName="";
                btn_Part.setText("未定义");
                btn_Reason.setText("未选择");
                break;
            case R.id.btn_Submit:
                System.out.println("btn_Submit");
                if (clampBarcode.getVisibility()==View.VISIBLE){
                    if (clampBarcode.getText().length()==0){
                        curToast.setText("请扫描返修夹子!");
                        curToast.show();
                        return;
                    }
                }
                SubmitQuestion();

                break;
            case R.id.btn_Part:
                showSelectPart();
                break;
            case R.id.btn_Reason:
                showSelectReason();
                break;
            default:
                break;
        }

    }

    //提交数据
    private void SubmitQuestion() {
        System.out.println("SubmitQuestion-1");
        if (ClipType.toUpperCase().equals("SINGLE")) {
            if (txt_QuestionCodes.getText().toString().indexOf("污") > -1
                    || txt_QuestionCodes.getText().toString().indexOf("破洞") > -1) {
                if (btn_Part.getText().toString().equals("未定义") || btn_Reason.getText().toString().equals("未选择")) {
                    curToast.setText(txt_QuestionCodes.getText().toString() + "必须要选部位及选原因!");
                    curToast.show();
                    return;
                }
            }
            System.out.println("SubmitQuestion 疵点:" + txt_QuestionCodes.getText().toString() + "indexOf(脱拷)" + txt_QuestionCodes.getText().toString().indexOf("脱拷"));
            if (txt_QuestionCodes.getText().toString().indexOf("脱拷") > -1) {
                if (btn_Part.getText().toString().equals("未定义")) {
                    curToast.setText(txt_QuestionCodes.getText().toString() + "必须要选部位!");
                    curToast.show();
                    return;
                }
            }
        }
        System.out.println("SubmitQuestion-2");
        if (NeedPos.equals("YES")&&points.size()==0) {
            curToast.setText("请在图片上标注疵点位置!");
            curToast.show();
            return;
        }
        if (points.size()==0&&ClipType.toUpperCase().equals("SINGLE")){
            PointPlace pointPlace1 = new PointPlace();
            pointPlace1.width_scale=0;
            pointPlace1.height_scale=0;
            points.clear();
            points.add(pointPlace1);
        }
        if (ClipType.toUpperCase().equals("SINGLE")==true){
            if (txt_QuestionCodes.getText().toString().indexOf("污")>-1
                    ||txt_QuestionCodes.getText().toString().indexOf("破洞")>-1){
                if (btn_Part.getText().toString().equals("未定义")||btn_Reason.getText().toString().equals("未选择")) {
                    curToast.setText(txt_QuestionCodes.getText().toString()+"必须要选部位及选原因!");
                    curToast.show();
                    return;
                }
            }
            if (txt_QuestionCodes.getText().toString().length()>0){
                try {
                    detailJson=new JSONArray("[]");
                    JSONObject tmpObj=new JSONObject();
                    tmpObj.put("RowNo",detailJson.length()+1);
                    tmpObj.put("Reason",btn_Reason.getText().toString());
                    tmpObj.put("QuestionCodes",txt_QuestionCodes.getText().toString());
                    tmpObj.put("PosX",points.get(0).width_scale);
                    tmpObj.put("PosY",points.get(0).height_scale);
                    tmpObj.put("PartName",btn_Part.getText().toString());
                    detailJson.put(tmpObj);
                    txt_QuestionCodes.setText("");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else{
                curToast.setText("请先选择疵点再提交!");
                curToast.show();
                return;
            }
        }
        if (ClipType.toUpperCase().equals("LARGE")==true){
            if (detailJson.length()==0) {
                curToast.setText("请先选择疵点并暂存！");
                curToast.show();
                return;
            }
        }
        //正式保存;
        if (detailJson.length()>0){
            //返回
            Intent intent = new Intent();
            intent.putExtra("questionJson",String.valueOf(detailJson));
            intent.putExtra("clampNo",clampBarcode.getText().toString());
            setResult(2001,intent);
            finish();
        } else{
            curToast.setText("请先选择疵点并暂存！");
            curToast.show();
        }
    }

    //获取明细
    private void GetQuestion() {
        //执行SQL过程
        tmpItemView=null;
        tmpItemIndex=-1;
        String SqlComm = "Exec KeyPoint_RepairGetQuestion @OPERTYPE='QUESTION',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }
    private void GetReason(String paramQuestion) {
        //执行SQL过程
        tmpItemView=null;
        tmpItemIndex=-1;
        String SqlComm = "Exec KeyPoint_RepairGetReason @OPERTYPE='REASON',@Question='" + paramQuestion+"',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //订单表格适配器;
    public final class TypeGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public TypeGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return typeJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return typeJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_question_type, null, false);
            int color = getResources().getColor(R.color.text_black);
            String tmpType="",tmpStr="";
            String tmpValue;
            try {
                Log.d("msg", "getView()a----------------------------------------------------->" + position);
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if ((typeJson.optJSONObject(position).has("QuestionType") == true)&&(view.findViewById(R.id.item_QuestionType)!=null)) {
                    ((TextView) view.findViewById(R.id.item_QuestionType)).setText(typeJson.optJSONObject(position).getString("QuestionType"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","TypeGridAdapter_position:"+position);
            //默认选中第0个，因为还没有确定界面，所以要延时选中;
            if (tmpItemView==null) {
                if (tmpType.length()==0) {
                    try {
                        tmpStr=typeJson.optJSONObject(position).getString("QuestionType");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (tmpStr.indexOf("缝制")>=0) {
                        tmpItemIndex=position;
                        tmpItemView=view;
                        tmpItemView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Log.d("msg","tmpItemView.postDelayed");
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_FocusDefaultItem;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                        }, 100);
                    }
                }
            }
            return view;
        }
    }
    //订单表格适配器;
    public final class ItemGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ItemGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return itemJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return itemJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_question_item, null, false);
            try {
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if ((itemJson.optJSONObject(position).has("QuestionNo") == true)&&(view.findViewById(R.id.item_QuestionNo)!=null)) {
                    ((TextView) view.findViewById(R.id.item_QuestionNo)).setText(itemJson.optJSONObject(position).getString("QuestionNo"));
                }
                if ((itemJson.optJSONObject(position).has("QuestionCode") == true)&&(view.findViewById(R.id.item_QuestionCode)!=null)) {
                    ((TextView) view.findViewById(R.id.item_QuestionCode)).setText(itemJson.optJSONObject(position).getString("QuestionCode"));
                }
                if ((itemJson.optJSONObject(position).has("QuestionNum") == true)&&(view.findViewById(R.id.item_QuestionNum)!=null)) {
                    if (!itemJson.optJSONObject(position).getString("QuestionNum").equals("0"))
                    ((TextView) view.findViewById(R.id.item_QuestionNum)).setText(itemJson.optJSONObject(position).getString("QuestionNum"));
                } else  ((TextView) view.findViewById(R.id.item_QuestionNum)).setText("");

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","ItemGridAdapter_position:"+position);
            return view;
        }
    }

    //订单表格适配器;
    public final class DetailListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public DetailListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return detailJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return detailJson.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.activity_question_listhead, null, false);

            try {
                Log.d(TAG, "getView()----------------------------------------------------->" + position);
                if ((detailJson.optJSONObject(position).has("RowNo") == true)&&(view.findViewById(R.id.item_RowNo)!=null)) {
                    ((TextView) view.findViewById(R.id.item_RowNo)).setText(String.valueOf(position+1));
                }
                if ((detailJson.optJSONObject(position).has("PartName") == true)&&(view.findViewById(R.id.item_PartName)!=null)) {
                    ((TextView) view.findViewById(R.id.item_PartName)).setText(detailJson.optJSONObject(position).getString("PartName"));
                }
                if ((detailJson.optJSONObject(position).has("QuestionCodes") == true)&&(view.findViewById(R.id.item_QuestionCodes)!=null)) {
                    ((TextView) view.findViewById(R.id.item_QuestionCodes)).setText(detailJson.optJSONObject(position).getString("QuestionCodes"));
                }
                if (tv_QuestionInv.getVisibility()==View.VISIBLE) {
                    if ((detailJson.optJSONObject(position).has("Reason") == true) && (view.findViewById(R.id.item_Reason) != null)) {
                        ((TextView) view.findViewById(R.id.item_Reason)).setText(detailJson.optJSONObject(position).getString("Reason"));
                    }
                } else view.findViewById(R.id.item_Reason).setVisibility(GONE);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","detailAdapter_position:"+position);
            return view;
        }
    }

    //显示工序选择
    private void showSelectPart(){
        if (partJson==null){
            curToast.setText("没有部位信息!");
            curToast.show();
            return;
        }
        if (NeedPos.equals("YES")){
            if (points.size()==0){
                curToast.setText("请先选择疵点!!");
                curToast.show();
                return;
            }
        }

        try {
            headJSON=new JSONArray("[{\"TitleName\":\"PartName\",\"TitleText\":\"部位名称\",\"TxtSize\":18,\"TxtWidth\":250,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}," +
                    "{\"TitleName\":\"PosX\",\"TitleText\":\"X-POS\",\"TxtSize\":18,\"TxtWidth\":80,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"},"+
                    "{\"TitleName\":\"PosY\",\"TitleText\":\"Y-POS\",\"TxtSize\":18,\"TxtWidth\":80,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        String dgCaption="部位选择";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        //创建表头;
        CreateListHead();
        selectItemJson=partJson;
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        selectTempletList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    view.setSelected(true);
                    if (selectItemJson.optJSONObject(position).has("PartName")==true)
                        selPartName=selectItemJson.optJSONObject(position).getString("PartName");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //显示表明细
        SelectTempletListAdapter selectTempletListAdapter=new SelectTempletListAdapter(this);
        selectTempletList.setAdapter(selectTempletListAdapter);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(selectTemplet).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selPartName.length() == 0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请点击要选择的内容！");
                            curToast.show();
                        } else{
                            btn_Part.setText(selPartName);
                            btn_Part.setBackground(getResources().getDrawable(R.drawable.btn_back_add));
                            //增加部位定义
                            if (points.size()>0) addPartPos(selPartName,points.get(0).width_scale*100,points.get(0).height_scale*100);
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    selPartName="";
                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;
        int height = metric.heightPixels;
        params.width = width/2;
        params.height = height*2/3 ;
        alterDialog.getWindow().setAttributes(params);
    }

    //显示工序选择
    private void showSelectReason(){
        try {
            headJSON=new JSONArray("[{\"TitleName\":\"Reason\",\"TitleText\":\"问题原因\",\"TxtSize\":18,\"TxtWidth\":250,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Blue\"}]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //创建布局
        String dgCaption="选择原因";
        LayoutInflater inflater=this.getLayoutInflater();
        final View selectTemplet=inflater.inflate(R.layout.select_templet, null);
        templetlisthead=selectTemplet.findViewById(R.id.templetlisthead);
        //创建表头;
        CreateListHead();
        //Activity.findViewById最终还是会调用View.findViewById
        selectTempletList=selectTemplet.findViewById(R.id.selectTempletList);
        selectTempletList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    view.setSelected(true);
                    if (selectItemJson.optJSONObject(position).has("Reason")==true)
                        selReason=selectItemJson.optJSONObject(position).getString("Reason");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(selectTemplet).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selReason.length() == 0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请点击要选择的内容！");
                            curToast.show();
                        } else{
                            btn_Reason.setText(selReason);
                            btn_Reason.setBackground(getResources().getDrawable(R.drawable.btn_back_add));
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
        ).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    selReason="";
                    Field field = null;
                    field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                    field.setAccessible(true );
                    field.set(dialog,true );
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                Log.v("tag","取消");
            }
        }).setTitle(dgCaption);
        final AlertDialog alterDialog =builder.create();
        alterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                //禁止两个按键上获取焦点，不然扫描框里就会失去焦点,在OnShow之前;
                System.out.println("alterDialog-setOnShowListener");
            }
        });
        alterDialog.show();
        //此处设置位置窗体大小
        WindowManager.LayoutParams params = alterDialog.getWindow().getAttributes();
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;
        int height = metric.heightPixels;
        params.width = width/2;
        params.height = height*2/3 ;
        alterDialog.getWindow().setAttributes(params);
        GetReason(txt_QuestionCodes.getText().toString());
    }

    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return selectItemJson.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<selectItemJson.length())
                    return selectItemJson.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.select_templet_item, null, false);
            //变换背景色
            /*
            if (position%2==1) {
                view.setBackgroundColor(getResources().getColor(R.color.content));
            }
            */
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams(pullVatListWidth,60));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<selectItemJson.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (selectItemJson.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = selectItemJson.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (selectItemJson.optJSONObject(curPosition).has(TitleName)==true) tmpValue= selectItemJson.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    curToast.setText( e.getMessage());
                    curToast.show();
                }
            }
            return view;
        }
    }

    //创建列;
    private void CreateListHead() {
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(this);
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else templetlisthead.addView(tv);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }


    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor=Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor=Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }


    //判断是否为数字
    public static boolean isNumer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_ViewHisDetail:
                    System.out.println("Enter MSG_ViewHisDetail"+detailJson.toString());
                    if (detailJson!=null&&detailJson.length()>0){
                        txt_QuestionCodes.setText("");
                        points.clear();
                        //显示
                        DetailListAdapter detailListAdapter=new DetailListAdapter(getApplicationContext());
                        detailList.setAdapter(detailListAdapter);
                        ptlayout.removeAllViews();
                        for (int i=0;i<detailJson.length();i++){
                            try {
                                float posX=Float.parseFloat(detailJson.optJSONObject(i).getString("PosX"));
                                float posY=Float.parseFloat(detailJson.optJSONObject(i).getString("PosY"));
                                ptlayout.addItem(Math.round(ptlayout.getWidth()*posX),Math.round(ptlayout.getHeight()*posY),
                                        detailJson.optJSONObject(i).getString("QuestionCodes"),String.valueOf(i),1,"L");
                                System.out.println("posX:"+posX+" PosY:"+posY);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        //if (points!=null&&points.size()>0) imageLayout.setPoints(points);
                    }
                    break;
                case MSG_ReasonOver:
                    //显示表明细
                    selectItemJson=reasonJson;
                    SelectTempletListAdapter selectTempletListAdapter=new SelectTempletListAdapter(selectTempletList.getContext());
                    selectTempletList.setAdapter(selectTempletListAdapter);
                    break;
                case MSG_QuestionOver:
                    GetType();
                    break;
                case MSG_FocusDefaultItem:
                    if ((tmpItemView!=null)&&(tmpItemIndex>-1)){
                        titleGrid.requestFocusFromTouch();
                        titleGrid.setSelection(tmpItemIndex);
                        titleGrid.requestFocus(tmpItemIndex);
                        titleGrid.getChildAt(tmpItemIndex).setSelected(true);
                        titleGrid.getChildAt(tmpItemIndex).setActivated(true);
                        titleGrid.performItemClick(titleGrid.getChildAt(tmpItemIndex), tmpItemIndex, titleGrid.getItemIdAtPosition(tmpItemIndex));
                        tmpItemIndex=-1;
                    }
                    break;
                default:
                    break;
            }
        }
    };
    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try{
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    //往界面转数据;
                    String OperType="";
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OPERTYPE")==true)
                            OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (jsonArray.optJSONObject(0).has("OperType")==true)
                            OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (OperType.toUpperCase().equals("QUESTION")) {
                            questionJson= jsonArray;
                            //将数据放到Part表中
                            if (tmpdb==null) OpenCreateDB();
                            try {
                                tmpdb.execSQL("Delete from QCQuestion");
                                for (int i=0;i<questionJson.length();i++) {
                                    tmpdb.execSQL("Insert into QCQuestion(QuestionNo,QuestionCode,TypeIndex,QuestionType) values(?,?,?,?)",
                                            new Object[]{questionJson.optJSONObject(i).getString("QuestionNo"),
                                                    questionJson.optJSONObject(i).getString("QuestionCode"),
                                                    questionJson.optJSONObject(i).getString("TypeIndex"),
                                                    questionJson.optJSONObject(i).getString("QuestionType"),
                                            });
                                }
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_QuestionOver;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            } catch (JSONException e) {
                                e.printStackTrace();
                                curToast.setText("QC代码暂存完成:\r\b"+e.getMessage());
                                curToast.show();
                            }
                        }
                        if (OperType.toUpperCase().equals("REASON")) {
                            reasonJson = jsonArray;
                            Message msg = new Message();
                            msg.what = MSG_ReasonOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();

    }


    //打开数据库
    public void OpenCreateDB(){
        if (tmpdb==null) {
            tmpdb = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        }
    }


}
